import RPi.GPIO as GPIO
import os,sys
import subprocess
import time


class BufferCapture:
  def __init__(self,
               buttonPin = 4,
               ledPin = 22,
               watchPin = 18,
               fileDirectory = "/tmp",
               filePrefix = "FILE_",
               runOnce = False):
    self.ledPinNum = ledPin
    self.watchingLedPin = watchPin
    self.buttonPinNum = buttonPin
    self.fileDirectory = fileDirectory
    self.filePrefix = filePrefix
    self.runOnce = runOnce
    self.fileNumber = 0

    # numbering scheme that corresponds to breakout board and pin layout
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)

    
    GPIO.setup(self.ledPinNum,GPIO.OUT)
    GPIO.output(self.ledPinNum,GPIO.HIGH)

    GPIO.setup(self.watchingLedPin, GPIO.OUT)
    GPIO.output(self.watchingLedPin,GPIO.LOW)

    #initialize the button pin
    GPIO.setup(self.buttonPinNum, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)


    #initialize the file that contains the number of the current file to write

    self.fileNumberCacheFile = "%s/.fileCache" % (self.fileDirectory)
    if os.path.exists(self.fileNumberCacheFile) == False:
      self.cacheFileNumber()
    else:
      self.readFileNumber()
  #end def

      

  def makeFileName(self,num):
    fileName = "%s/%s%04d.h264" % (self.fileDirectory, self.filePrefix,num)
    return fileName
  #end def


  def cacheFileNumber(self):
    f = open(self.fileNumberCacheFile, 'w')
    f.write("%d\n"% (self.fileNumber))
    f.close()
  #end def

  def readFileNumber(self):
    f = open(self.fileNumberCacheFile, 'r')
    fileNumberString = f.readline()
    f.close()
    self.fileNumber = int(fileNumberString)
    print "Found previous images starting at %d\n" %(self.fileNumber)
  #end def

    
  def signalCapture(self):
    GPIO.output(self.watchingLedPin,GPIO.HIGH)
    os.system("killall raspivid -s SIGUSR1 &")
  #end def

  def startCapture(self):


    #set up the video capture into the buffer
    fileName = self.makeFileName(self.fileNumber)
    self.cacheFileNumber()
    
    
    print  "%s is being printed " % (fileName)
    command = "raspivid -c -s -t 10000 -o %s &" % (fileName)
    os.system(command)
    GPIO.output(self.watchingLedPin, GPIO.LOW)
  #end def

  def waitBlink(self, pin, times):
  
    for i in range(0,times):
      time.sleep(0.25)
      if pin > 0:
        GPIO.output(pin,GPIO.LOW)
      else:
        print ".";
        
      time.sleep(0.25)
      if pin >0:
        GPIO.output(pin,GPIO.HIGH)
      else:
        print "."
        
      #endfor
    #endif
  #end def

  '''
  The main body of the program.
  Starts a capture and then waits for the button
  to be pressed.
  '''
  def mainLoop(self):

    self.startCapture()

    print "started camera press button to record"
    done = False
    while not done:
      input = GPIO.input(self.buttonPinNum)

      if (input):
        print "Sending Signal"
        self.signalCapture()
        
        self.waitBlink(self.ledPinNum, 10)
           
        if self.runOnce:
          done = True
          print "One time run, exiting"
        else:
          print "Restarting the capture again"
          self.fileNumber += 1
          self.startCapture()
        #end if
      #endif
    #end while
  #end mainLoop

def main(argv):
  grabber = BufferCapture()
  grabber.mainLoop()
#end def

  
if __name__ == "__main__":
    sys.exit(main(sys.argv))


